package com.example.demo.utils;

import com.example.demo.entity.Menu;
import com.example.demo.entity.TreeNode;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class TreeUtil {
    public static <T extends TreeNode> List<T> build(List<T> treeNodes, Long pid){
        Assert.notNull(pid,"节点错误");
        List<T> treeList = new ArrayList<>();
        for (T treeNode:treeNodes){
            if (pid.equals(treeNode.getPid())){
                treeList.add(findChildren(treeNodes,treeNode));
            }
        }
        return treeList;
    }
    /**
     * 查找子节点
     */
    private static <T extends TreeNode> T findChildren(List<T> treeNodes, T rootNode) {
        for(T treeNode : treeNodes) {
            if(rootNode.getId().equals(treeNode.getPid())) {
                rootNode.getChildren().add(findChildren(treeNodes, treeNode));
            }
        }
        return rootNode;
    }

    /**
     * 构建树节点
     */
    public static <T extends TreeNode> List<Menu> build(List<Menu> treeNodes) {
        List<Menu> result = new ArrayList<>();

        //list转map
        Map<Integer, Menu> nodeMap = new LinkedHashMap<>(treeNodes.size());
        for(Menu treeNode : treeNodes){
            nodeMap.put(treeNode.getId(), treeNode);
        }

        for(Menu node : nodeMap.values()) {
            Menu parent = nodeMap.get(node.getPid());
            if(parent != null && !(node.getId().equals(parent.getId()))){
                parent.getChildren().add(node);
                continue;
            }
            result.add(node);
        }

        return result;
    }


}
